package EventDispatchers
{
	import Events.ImageEvent;
	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	
	import flash.display.Bitmap;
	
	public class ImageLoader extends EventDispatcher
	{
		private var loader:Loader;
		
		public function ImageLoader(target:IEventDispatcher=null)
		{
			super(target);
			loader = new Loader();
		}
		
		public function Load($url:String):void
		{
			var request:URLRequest;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
			loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			
			//--Load xml request
			request = new URLRequest($url);
			var header:URLRequestHeader = new URLRequestHeader("pragma", "no-cache");
			request.requestHeaders.push(header);
			loader.load(request);
		}
		
		private function loadComplete(e:Event):void
		{
			var bitmap:Bitmap = Bitmap(LoaderInfo(e.target).content);
			dispatchEvent(new ImageEvent(ImageEvent.IMAGELOADED, bitmap));
			
			complete();
		}
		
		
		private function ioError(e:IOErrorEvent):void
		{
			trace( "ImageLoader failed because of IO error: " + e.text);
			
			complete();
		}
		
		private function securityError(e:SecurityErrorEvent):void
		{
			trace( "ImageLoader failed because of security error: " + e.text);
			
			complete();
		}
		
		private function complete():void
		{
			//--Remove listeners
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, loadComplete);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			loader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			
			//--Destroy
			destroy();
		}
		
		private function destroy():void {
			loader = null;
		}
	}
}